<?php
namespace app\index\controller;

use app\admin\model\Lonlat;
use app\common\controller\Frontend;
use EasyWeChat\Factory;
use fast\Random;
use think\Config;
use think\Session;


class Demo extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $noNeedWechat = ['oauth','wechathandle'];
    protected $layout = '';
    protected $app;

    public function _initialize()
    {
        parent::_initialize();

        $config = array_merge(Config::get('wechatConfig'),[
                'oauth' => [
                    'scopes'   => ['snsapi_base'],
                    'callback' => url('/index/demo/wechathandle'),
                ],
            ]
        );
        $this -> app = Factory::officialAccount($config);
        // 获取 access token 实例
//        $accessToken = $this -> app->access_token; // EasyWeChat\Core\AccessToken 实例
//        $token = $accessToken->getToken(); // token 字符串

        $action = $this -> request -> action();
        if(
            //defined('CHECKWECHAT') && CHECKWECHAT &&
            is_null(Session::get('wechatUser')) &&
            !in_array($action,$this -> noNeedWechat)
        ){
            Session::set('redirectUrl',url($this -> request -> action()));
            $this -> redirect(url('oauth'));
        }
        $openid = Session::get('wechatUser')['openid'];
        $user = \app\admin\model\User::getByOpenid($openid);
        Session::set('frontUser',$user);
    }


    public function index(){

        $data = json_decode('{"uid":9,"openid":"o6kZq07fR9WdopDmBgpP3rIlPutA","latitude":"36.305637","longitude":"120.470673","precision":"65.000000","formatted_address":"\u5c71\u4e1c\u7701\u9752\u5c9b\u5e02\u57ce\u9633\u533a\u94c1\u9a91\u5c71\u8def","city":"\u9752\u5c9b\u5e02","province":"\u5c71\u4e1c\u7701","district":"\u57ce\u9633\u533a","street":"\u94c1\u9a91\u5c71\u8def"}',true);

       // (new Lonlat) -> save($data);


//        return $this -> fetch();
    }



    public function oauth(){
        $oauth = $this -> app->oauth;

        $response = $oauth->scopes(['snsapi_userinfo'])
            ->redirect();
        $response -> send();
    }

    public function wechathandle(){
        $oauth = $this -> app->oauth;

        $_user = $oauth -> user() -> toArray();
        $_userw = $this -> app -> user->get($_user['id']);
        Session::set('wechatUser',$_userw);
        $user = \app\admin\model\User::getByOpenid($_user['id']);
        if(!$user){
            $extend = [
                'openid'    => $_user['id'],
                'headimgurl'    => $_user['original']['headimgurl'],
                'sex'       => $_user['original']['sex'],
                'city'      => $_user['original']['city'],
                'province'  => $_user['original']['province'],
                'country'    => $_user['original']['country'],
                'is_sub'    => $_userw['subscribe']
            ];
            $this->auth->register($_user['name'], '123456', Random::alnum().Random::alnum().'@163.com', '',$extend);
        }

        $url = Session::get('redirectUrl') ? Session::get('redirectUrl') : url('index');
        $this -> redirect($url);
    }

}
